<?php
/**
 * Created by PhpStorm.
 * User: 杨永安
 * Date: 2017/3/26
 * Time: 19:56
 */

namespace app\api\controller;


use Flc\Alidayu\Client;
use Flc\Alidayu\App;
use Flc\Alidayu\Requests\AlibabaAliqinFcSmsNumSend;
use Flc\Alidayu\Requests\IRequest;
use think\Log;

class Sms
{
    function get($phone, $verify_str, $verify_time)
    {
        $config = [
            'app_key' => db('system_config')->where('name','sms_ali_key')->value('value'),
            'app_secret' => db('system_config')->where('name','sms_ali_secret')->value('value'),
            // 'sandbox'    => true,  // 是否为沙箱环境，默认false
        ];
        $verify_db = db('verify_code')->where('account', $phone)->find();
        $code = rand(1000, 9999);
        if ($verify_db) {
            if (time() - $verify_db['time'] <= 600) {
                $code = $verify_db['code'];
            } else {
                db('verify_code')->update(['account' => $phone, 'code' => $code, 'time' => time()]);
            }
        }
        $client = new Client(new App($config));
        $req = new AlibabaAliqinFcSmsNumSend;
        $req->setRecNum($phone)->setSmsParam([
            'code' => $code,
            'product' => 'speedUp'
        ])->setSmsFreeSignName('水木易安')
            ->setSmsTemplateCode('SMS_62195029');
        if ($verify_str == md5($verify_time . 'sms') && time() - $verify_time <= 60) {
            $resp = $client->execute($req);
            $object = json_decode(json_encode($resp), true);
            if (array_key_exists('result', $object)) {//如果成功就保存验证到数据库
                if (!$verify_db) {
                    $data['account'] = $phone;
                    $data['code'] = $code;
                    $data['time'] = time();
                    db('verify_code')->insert($data);
                }
            }
        } else {
            $resp['code'] = -1000;
            $resp['msg'] = '获取验证码已经超时';
            $resp['sub_msg'] = "请在60秒内完成获取,请点击确认刷新.";
        }

        Log::info('[SMS]phone:' . $phone . ' time:' . date('m-d h:i:s', time()));
        return json($resp);

    }
}